<?php
declare (strict_types = 1);
namespace app\adminapi\logic\system\auth;
use adminmatrix\server\app\logic\BaseLogic;
use adminmatrix\annotation\Inject;
use app\adminapi\model\system\auth\AdminRolePermission;
use app\adminapi\model\system\auth\Permission;
use app\adminapi\model\system\auth\Role as RoleModel;
use think\exception\HttpException;
use think\Request;
use think\facade\Db;
class RoleLogic extends BaseLogic
{
    #[Inject]
    protected RoleModel $model;


    public function setAuth(Request $request) : bool
    {
        Db::startTrans();
        try {
            $role = $request->put('role');
            $id   = $request->put('id');
            $data = $this->model ->findOrEmpty($id);
            $roleAll = [];
            foreach ($role as $roleId)
            {
                $roleAll[]   = [
                    'permission_id'   =>  $roleId,
                    'role_id'           => $id
                ];
            }
            $data->role()->where('role_id' , $id)->delete();
            $data->role()  ->saveAll($roleAll);
                        // 提交事务
            Db:: commit();

            return true;
        } catch (HttpException $e)
        {
            // 回滚事务
            Db::rollback();
            return throw new HttpException(200 , $e->getMessage());
        }

    }


    public static function getBtnAuthByRoleId($admin) :array
    {
        if ($admin['root'])
        {
            return ['*'];
        }

        $menuId = AdminRolePermission::whereIn('role_id' , $admin->role->column('role_id'))->column('permission_id');
        $where [] = ['perms' , "<>" , ""];

        $roleAuth = Permission::distinct(true)
            ->whereIn('id' , $menuId )
            ->where($where)
            ->column('perms');

        $allAuth = Permission::distinct(true)
            ->where($where)
            ->column('perms');

        $hasAllAuth = array_diff($allAuth , $roleAuth);
        if (empty($hasAllAuth)) return  ["*"];
        return $roleAuth;

    }

}